$(function(){

  var loginNode = $('#login'),
    submitNode = $('#submit'),
    formNode = $('#form'),
    resultNode = $('#result'),
    listNode = $('#list'),
    loadingNode = $('#loading').hide(),
    noticeNode = $('#notice'),
    backNode = $('#back'),
    vcLayerNode = $('#vcLayer'),
    vcImgNode = $('#vcImg'),
    vcInputNode = $('#vcInput'),
    loadMoreNode = $('#loadMore'),
    qzoneUrl = 'http://user.qzone.qq.com/',

    qqNode = $('#qq').focus(),
    passNode = $('#pass'),
    termsNode = $('#terms'),
    qvPageNode = $('#qvPage'),//翻页参数

    /* 提交请求中 */
    getVisitors = function(){
      submitNode.addClass('disabled');
      loadingNode.show();
    },

    /* 请求已响应 */
    getVisitorsOver = function(ok){
      submitNode.removeClass('disabled');
      loadingNode.hide();

      if(ok){
        loginNode.hide();
        resultNode.show();
      };
    },

    //验证码刷新
    refreshVerifycode = function(){
      vcImgNode.attr('src',
        '/getVerifycodeImg?qq='+qqNode.val()+'&cap_cd='+ vcImgNode.attr('cap_cd') +
        '&r=' + Math.random()
      );

      vcInputNode.focus();
    };

  vcImgNode.on('click', refreshVerifycode);


  //格式化时间，使其更只管
  function formatTime(time){
    var costtime = parseInt(+new Date() / 1000) - time, //单位 秒
      num = 0,
      formatedTime = '';

    if(costtime <= 60){
      formatedTime = '刚才';

    }else if(costtime <= 3600 ){ // 1小时内
      num = window.parseInt(costtime / 60);
      formatedTime = num + '分钟前';

    }else if(costtime <= 24 * 3600 ){ // 1天内
      num = window.parseInt(costtime / (3600));
      formatedTime = num + '小时前';

    }else{ // 超过一天，返回具体时间
      formatedTime = new Date(time * 1000).toLocaleString();
    };

    return formatedTime;
  };

  //查看是否记住帐号密码
  if($.cookie('qq')){
    qqNode.val($.cookie('qq'));
    passNode.val($.cookie('pass'));

    termsNode.prop('checked', true);
  };

  submitNode.removeClass('disabled')
    .on('click', function(){
      formNode.submit();
    });

  //获取更多访客
  loadMoreNode.on('click', function(){

    //没有更多访客了就不做操作
    if(!qvPageNode.val()) return;

    formNode.trigger('submit', {mode: 'loadMore'});
  });

  //返回填写帐号信息界面
  backNode.on('click', function(){
    resultNode.hide();
    loginNode.show();
    qqNode.focus();

    noticeNode.html('友情提示：请不要频繁使用同一个帐号登录')
      .removeClass('red');
  });

  //获取访客请求发送
  formNode.on('submit', function(e, mode){
    getVisitors();

    if(vcLayerNode.css('display') == 'none'){
      vcInputNode.val('');
    };

    $.ajax({
      url: formNode.attr('action') + (mode ? mode.mode : ''),
      data: formNode.serialize(),
      type: 'post',
      dataType: 'json',
      timeout: 10000, //超时时间 10秒
      success: function(data){
        var visitorList,
          sHtml = '',
          cookieTimeout,
          domAction = 'html',
          isOk = false;

        noticeNode.html(data.msg);

        if(data.status == 'success'){

          vcLayerNode.hide();

          //记住帐号密码
          if(termsNode.prop('checked')){

            //存储一个带7天期限的cookie
            cookieTimeout = new Date();
            cookieTimeout.setTime(cookieTimeout.getTime() + (3600 * 24 * 7 * 1000));

            $.cookie("qq", data.qq, { expires: cookieTimeout });
            $.cookie("pass", data.pass, { expires: cookieTimeout });

          }else{

            $.cookie("qq", "", { expires: -1 });
            $.cookie("pass", "", { expires: -1 });

          };

          visitorList = data.visitors.data.visit.datalist;

          if(visitorList && visitorList.length){
            isOk = true;

            for(var i=0,len=visitorList.length;i<len;i++){

              //突破防盗链，服务器代理获取图片
              var face = visitorList[i].face;
              face = '/getFace?faceUrl=' + encodeURIComponent(face);

              sHtml += '<div class="comment">'+
                '<a class="avatar" href="'+ qzoneUrl + visitorList[i].uin +'" target="_blank">'+
                '<img class="face error" src="'+ face +'" />'+
                '</a>'+
                '<div class="content">'+
                '<a class="author" href="'+ qzoneUrl + visitorList[i].uin +'" target="_blank">'+
                visitorList[i].nickname + '(' + visitorList[i].uin + ')'+
                '</a>'+
                '<div class="metadata">'+
                '<span class="date">'+ formatTime(visitorList[i].vtime) +'</span>'+
                '</div>'+
                '<div class="text">TA的操作：'+ visitorList[i].visit_info +'</div>'+
                '</div>'+
                '</div>'+
                '</div>';
            };

            if(data.mode == 'loadMore'){
              domAction = 'append';
            }else{
              loadMoreNode.html('加载更多访客');
            };

            qvPageNode.val(data.visitors.data.page);//设置下一页查找参数
            listNode[domAction](sHtml);

          }else{//没有访客了

            if(data.mode == 'loadMore'){
              loadMoreNode.html('没有更多访客了');
            };

            qvPageNode.val('');
            noticeNode.html('暂无被拦访客');
          };

        }else{//登录失败

          if(data.type == 'refresh'){ //刷新验证码
            refreshVerifycode();

          }else if(data.cap_cd){ //获取验证码

            vcImgNode.attr('src', '/getVerifycodeImg?qq='+qqNode.val()+'&cap_cd='+ data.cap_cd)
              .attr('cap_cd', data.cap_cd);

            vcLayerNode.show();

            vcInputNode.focus();
          };
        };

        getVisitorsOver(isOk);

        isOk ?
          noticeNode.removeClass('red') :
          noticeNode.addClass('red');

      },

      error: function(XMLHttpRequest, textStatus, errorThrown){

        if(textStatus == 'timeout'){
          noticeNode.html('获取超时，请稍后访问');

        }else if(textStatus == 'error'){
          noticeNode.html('服务器抽风了，请稍后访问');
        };

        noticeNode.addClass('red');

        getVisitorsOver();
      }

    });

    e.preventDefault();
    return false;
  });

  //捐款提示
  $('#donate').popup({
    on: 'click',
    position: 'bottom center',
    title: '捐赠',
    content: '如果本网站能帮助到您，您可以选择捐款犒劳作者：likenovel@qq.com，<a href="https://shenghuo.alipay.com/send/payment/fill.htm" target="_blank">请点击这里</a>'
  });

});